<template>
    <div class="content-page">
        <div class="content-nav">
            <el-breadcrumb class="breadcrumb" separator="/">
                <el-breadcrumb-item :to="{ path: '/dashboard' }">首页</el-breadcrumb-item>
                <el-breadcrumb-item>病历管理</el-breadcrumb-item>
                <el-breadcrumb-item>{{infoForm.id ? '编辑病历' : '新建病历'}}</el-breadcrumb-item>
            </el-breadcrumb>
            <div class="operation-nav">
                <el-button type="primary" @click="goBackPage" icon="arrow-left">返回列表</el-button>
            </div>
        </div>
        <div class="content-main">
            <div class="form-table-box">
                <el-form ref="infoForm" :rules="infoRules" :model="infoForm" label-width="120px">
                    <el-form-item label="手机号" prop="phone">
                        <el-autocomplete :trigger-on-focus="false" :fetch-suggestions="searchAsync"
                                         v-model="infoForm.phone" placeholder="请输入手机号"
                                         @select="handleSelect" clearable>
                            <template slot-scope="{item}">
                                <div>{{item.phone}}</div>
                                <span>{{item.name}}</span>
                            </template>
                        </el-autocomplete>
                    </el-form-item>
                    <el-form-item label="用户信息" prop="detail">
                        <el-input v-model="infoForm.detail" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="免疫情况" prop="pet_immune">
                        <el-select v-model="infoForm.pet_immune" placeholder="请选择免疫类型">
                            <el-option v-for="item in immuneType" :key="item.id" :label="item.name" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="病历类型" prop="type_path">
                        <el-cascader ref="type_path" :options="category" v-model="infoForm.type_path"
                                     change-on-select :props="props"></el-cascader>
                    </el-form-item>
                    <el-form-item label="日期" prop="date">
                        <el-date-picker type="date" v-model="infoForm.date" placeholder="选择日期" clearable
                                        value-format="timestamp">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="复诊日期" prop="date">
                        <el-date-picker type="date" v-model="infoForm.next_date" placeholder="选择日期" clearable
                                        value-format="timestamp">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="是否提醒" prop="is_notify">
                        <el-switch v-model="infoForm.is_notify"></el-switch>
                    </el-form-item>
                    <el-form-item label="简要描述" prop="simple_desc">
                        <el-input type="textarea" v-model="infoForm.simple_desc" :rows="3"></el-input>
                        <div class="form-tip"></div>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="onSubmitInfo">{{infoForm.id ? '更新' : '新建'}}</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>
    </div>
</template>

<script>
export default {
  data () {
    return {
      // uploaderHeader: {
      //   'X-Nideshop-Token': localStorage.getItem('token') || ''
      // },
      user_id: 0,
      infoForm: {
        id: 0,
        phone: '',
        detail: '',
        pet_immune: '',
        date: '',
        next_date: '',
        type: '',
        type_path: [0],
        is_notify: true,
        simple_desc: ''
      },
      category: [
        {
          id: 0,
          name: '顶级分类'
        }
      ],
      props: {
        value: 'id',
        label: 'name',
        children: 'child'
      },
      immuneType: [
        {
          id: 0,
          name: '未免疫'
        },
        {
          id: 1,
          name: '年度免疫'
        },
        {
          id: 2,
          name: '首免第一针'
        },
        {
          id: 3,
          name: '首免第二针'
        },
        {
          id: 4,
          name: '首免第三针'
        },
        {
          id: 5,
          name: '首免第四针'
        },
        {
          id: 6,
          name: '已免疫'
        }
      ],
      infoRules: {
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' }
        ],
        pet_immune: [
          { required: true, message: '请输入免疫信息', trigger: 'blur' }
        ],
        date: [
          { required: true, message: '请选择日期', trigger: 'blur' }
        ],
        next_date: [
          { required: true, message: '请选择复诊日期', trigger: 'blur' }
        ],
        type_path: [
          { required: true, message: '请输入病历类型', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    goBackPage () {
      this.$router.go(-1)
    },
    searchAsync (queryStr, cb) {
      this.$db.users.find({phone: new RegExp(queryStr)}, (err, docs) => {
        if (err) console.error('kumeng: ' + err.stack)
        cb(docs)
      })
    },
    handleSelect (item) {
      const currentDate = new Date()
      const year = currentDate.getFullYear()
      const month = currentDate.getMonth()
      const petBirthday = new Date(item.pet_birthday)
      const diff = currentDate.setFullYear(year - petBirthday.getFullYear(), month - petBirthday.getMonth())
      const diffDate = new Date(diff)
      const age = diffDate.getFullYear() + diffDate.getMonth() / 12
      this.infoForm.phone = item.phone
      this.infoForm.detail = item.name + '/'
      this.infoForm.detail += item.pet_name + '/'
      this.infoForm.detail += age + '/'
      this.infoForm.detail += item.pet_sex === 1 ? '公' : '母' + '/'
      this.infoForm.detail += item.pet_type
      // 免疫信息
      this.$db.immune.find({phone: this.infoForm.phone}).projection({type: 1}).sort({date: -1}).limit(1).exec((err, docs) => {
        if (err) console.error('kumeng: ' + err.stack)
        if (docs && docs.length) {
          this.infoForm.pet_immune = docs[0].type
        }
      })
    },
    onSubmitInfo () {
      this.$refs['infoForm'].validate((valid) => {
        if (valid) {
          this.getType()
          if (this.infoForm.id) {
            this.$db.records.update({id: this.infoForm.id}, this.infoForm, (err, count) => { // update 返回更新数
              if (err) console.error('kumeng: ' + err.stack)
              if (count) {
                this.$message({
                  type: 'success',
                  message: '更新成功'
                })
                this.$router.go(-1)
              }
            })
          } else {
            this.$db.records.find({}).projection({id: 1}).sort({id: -1}).limit(1).exec((err, docs) => {
              if (err) console.error('kumeng: ' + err.stack)
              if (docs && docs.length) { // 获取id的最大值后加1
                this.infoForm.id = docs[0].id + 1
              } else { // 如果是第一个数据，id=1
                this.infoForm.id = 1
              }
              this.$db.records.insert(this.infoForm, (err, doc) => { // insert 返回插入对象
                if (err) console.error('kumeng: ' + err.stack)
                if (doc) {
                  this.$message({
                    type: 'success',
                    message: '新建成功'
                  })
                  this.$router.go(-1)
                }
              })
            })
          }
        } else {
          return false
        }
      })
    },
    getType () {
      const labels = this.$refs['type_path'].currentLabels
      this.infoForm.type = ''
      for (let i = 0; i < labels.length; i++) {
        this.infoForm.type += labels[i] + '/'
      }
      this.infoForm.type = this.infoForm.type.substring(0, this.infoForm.type.length - 1)
    },
    async getCategory () {
      let top = await this.findCategoryWithParentId(0, 0)
      for (let i = 0; i < top.length; i++) {
        top[i].child = await this.findCategoryWithParentId(top[i].id, 2)
        if (top[i].child) {
          for (let j = 0; j < top[i].child.length; j++) {
            top[i].child[j].child = await this.findCategoryWithParentId(top[i].child[j].id, 2)
          }
        }
      }
      console.log('getCategory1: ' + JSON.stringify(top))
      this.category = this.category.concat(top)
    },
    async findCategoryWithParentId (parentId, type) {
      let query = {parent_id: parentId}
      if (type !== 0) query.type = type
      let result = await this.$db.category.asyncFind(query).then(docs => {
        if (docs && docs.length) {
          return docs
        }
      })
      return result
    },
    getInfo () {
      if (this.infoForm.id) {
        // 加载病历详情
        this.$db.records.find({id: this.infoForm.id}, (err, data) => {
          if (err) console.error('kumeng: ' + err.stack)
          if (data && data.length) {
            this.infoForm = data[0]
          }
        })
      }
      if (this.infoForm.phone) {
        this.$db.users.find({phone: this.infoForm.phone}, (err, docs) => {
          if (err) console.error('kumeng: ' + err.stack)
          if (docs && docs.length) {
            this.handleSelect(docs[0])
          }
        })
        this.$db.immune.find({phone: this.infoForm.phone}).projection({type: 1}).sort({date: -1}).limit(1).exec((err, docs) => {
          if (err) console.error('kumeng: ' + err.stack)
          if (docs && docs.length) {
            this.infoForm.pet_immune = docs[0].type
          }
        })
      }
      if (!this.infoForm.date) this.infoForm.date = new Date().getTime()
    }
  },
  components: {},
  mounted () {
    this.infoForm.id = this.$route.query.id || 0
    this.infoForm.phone = this.$route.query.phone || ''
    this.getInfo()
    this.getCategory()
  },
  name: 'RecordAddPage'
}
</script>

<style scoped>

</style>
